package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.exception.RRException;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryService")
@Transactional(rollbackFor = Exception.class)
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CategoryServiceImpl.class);
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    /*
        @Resource
        private CategoryDao categoryDao;
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //获取第一级的分类
        List<CategoryEntity> levelMenus = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0).map((menu) -> {
                    menu.setChildren(getChildern(menu, categoryEntities));
                    return menu;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) -
                            (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return levelMenus;
    }


    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildern(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childern = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //递归知道子菜单
            categoryEntity.setChildren(getChildern(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) -
                    (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return childern;
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        try {
            //TODO 1,检查这里的ids是否在其他地方引用
            int effnum = this.baseMapper.deleteBatchIds(asList);
            LOGGER.info(effnum + "--->>是否删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("请勾选上需要删除的菜单！");
        }
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> findpath = this.findParentPath(catelogId, paths);
        Collections.reverse(findpath);
        return (Long[]) findpath.toArray(new Long[findpath.size()]);
    }

    @Override
    public void updateCascode(CategoryEntity category) {
        this.baseMapper.updateById(category);
        if (!StringUtils.isEmpty(category.getCatId())) {
            //更新分类表和品牌表的名称
            categoryBrandRelationService.updateCategoryName(category.getCatId(), category.getName());
            //TODO 如果需要还要更改其他表的分明名
        }

    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }


}